<?php

namespace app\shop\controller\statistics;

use app\shop\controller\Controller;
use app\common\service\statistics\OrderService;
use app\common\service\statistics\ProductRankingService;
use app\shop\model\supplier\Supplier as SupplierModel;

/**
 * 销售数据控制器
 */
class Sales extends Controller
{
    /**
     * 销售数据统计
     */
    public function index()
    {

        //新增可以选择商户查看统计（kevin 2024/5/8）
        $params = $this->postData();
        $map = [];
        if (isset( $params['search']) && $params['search'] !='') {
            $map[] = ['name', '=', trim($params['search'])];
        }
        $shop_supplier_id = 0;
        if($map){
            $shop_supplier_id = (new SupplierModel())->where($map) -> value('shop_supplier_id');
        }

        return $this->renderSuccess('', [
            // 成交订单统计
            'order' => (new OrderService($shop_supplier_id))->getData(),
            // 成交商品统计
            'product' => (new OrderService($shop_supplier_id))->getProductData(),
            // 销量top10
            'productSaleRanking' => (new ProductRankingService())->getSaleRanking($shop_supplier_id),
            // 浏览top10
            'productViewRanking' => (new ProductRankingService())->getViewRanking($shop_supplier_id),
            // 退款top10
            'productRefundRanking' => (new ProductRankingService())->getRefundRanking($shop_supplier_id),
        ]);
    }

    /**
     * 通过时间段查询本期上期金额
     * $type类型：order refund
     */
    public function order($search_time, $type = 'order',$search ='')
    {
        $days = $this->getDays($search_time);
        $data = [];

        //新增可以选择商户查看统计（kevin 2024/5/8）
        $params = $this->postData();
        $map = [];
        if ($search !='') {
            $map[] = ['name', '=', trim($search)];
        }
        $shop_supplier_id = 0;
        if($map){
            $shop_supplier_id = (new SupplierModel())->where($map) -> value('shop_supplier_id');
        }


        if($type == 'order'){
            $data = (new OrderService($shop_supplier_id))->getDataByDate($days);
        }else if($type == 'refund'){
            $data = (new OrderService($shop_supplier_id))->getRefundByDate($days);
        }
        return $this->renderSuccess('', [
            // 日期
            'days' => $days,
            // 数据
            'data' => $data,
        ]);
    }


    /**
     * 导出
     */
    public function orderExport($search_time, $type = 'order',$search)
    {
        $days = $this->getDays($search_time);

        $map = [];
        if ($search !='') {
            $map[] = ['name', '=', trim($search)];
        }
        $shop_supplier_id = 0;
        if($map){
            $shop_supplier_id = (new SupplierModel())->where($map) -> value('shop_supplier_id');
        }
        if($type == 'order'){
            $title = '成交情况统计';
            $xls_cell = [
                ['day' , '时间'],
                ['total_money' , '成交金额'],
                ['total_num' , '成交量'],
                ['shop_supplier_name' , '商户'],
                ['store_name_str' , '门店']
            ];
            $list = (new OrderService($shop_supplier_id))->getDataByDate($days);
        }else if($type == 'refund'){
            $title = '退单情况统计';
            $xls_cell = [
                ['day' , '时间'],
                ['total_money' , '退单金额'],
                ['total_num' , '退单量'],
                ['shop_supplier_name' , '商户'],
                ['store_name_str' , '门店']
            ];
            $list = (new OrderService($shop_supplier_id))->getRefundByDate($days);
        }
        $exp_title = $title . date('Y-m-d H:i:s');
        exportExcel($exp_title, $xls_cell, $list);
    }

    /**
     * 通过时间段查询本期上期金额
     */
    public function product($search_time)
    {
        $days = $this->getDays($search_time);

        //新增可以选择商户查看统计（kevin 2024/5/8）
        $params = $this->postData();
        $shop_supplier_id = 0;
        if(isset($params['shop_supplier_id']) && $params['shop_supplier_id']){
            $shop_supplier_id = $params['shop_supplier_id'];
        }

        return $this->renderSuccess('', [
            // 日期
            'days' => $days,
            // 数据
            'data' => (new OrderService($shop_supplier_id))->getProductDataByDate($days),
        ]);
    }


    /**
     * 导出
     */
    public function productExport($search_time)
    {
        $shop_supplier_id = 0;
        if(isset($params['shop_supplier_id']) && $params['shop_supplier_id']){
            $shop_supplier_id = $params['shop_supplier_id'];
        }

        $days = $this->getDays($search_time);
        $list =  (new OrderService($shop_supplier_id))->getProductDataByDate($days);
        $xls_cell = [
            ['day' , '时间'],
            ['total_num' , '商品数']
        ];
        $exp_title = '已付款商品统计' . date('Y-m-d H:i:s');
        exportExcel($exp_title, $xls_cell, $list);
    }

    /**
     * 获取具体日期数组
     */
    private function getDays($search_time)
    {
        //搜索时间段
        if(!isset($search_time) || empty($search_time)){
            //没有传，则默认为最近7天
            $end_time = date('Y-m-d', time());
            $start_time = date('Y-m-d', strtotime('-7 day',time()));
        }else{
            $start_time = array_shift($search_time);
            $end_time = array_pop($search_time);
        }

        $dt_start = strtotime($start_time);
        $dt_end = strtotime($end_time);
        $date = [];
        $date[] = date('Y-m-d', strtotime($start_time));
        while($dt_start < $dt_end) {
            $date[] = date('Y-m-d', strtotime('+1 day',$dt_start));
            $dt_start = strtotime('+1 day',$dt_start);
        }
        return $date;
    }
}